<template>
  <el-form :inline="true" label-width="70px">
    <el-form-item label="一级分类">
      <!-- 必须给 select 绑定 v-model 属性 -->
      <el-select v-model="category1Id" placeholder="请选择一级分类" @change="getCategory2List">
        <!-- label：显示的名字 -->
        <!-- value：选中以后的值 -->
        <el-option
          v-for="item in category1List"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="二级分类">
      <el-select v-model="category2Id" placeholder="请选择二级分类" @change="getCategory3List">
        <el-option
          v-for="item in category2List"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="三级分类">
      <el-select v-model="category3Id" placeholder="请选择三级分类">
        <el-option
          v-for="item in category3List"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { onMounted } from 'vue'
import { storeToRefs } from 'pinia'
// 将 Store 引入
import { useCategoryStore } from '@/stores/category'
// 对 Store 进行实例化
const categoryStore = useCategoryStore()
// 使用 storeToRefs 将 Store 中的数据进行解构
const { category1List, category1Id, category2List, category2Id, category3List, category3Id } =
  storeToRefs(categoryStore)

// 获取二级分类数据
const getCategory2List = () => {
  // 一级分类切换，需要重置二级、三级的数据
  category2List.value = category3List.value = []
  category2Id.value = category3Id.value = ''

  // 调用 action，获取二级分类数据
  // console.log(category1Id.value)
  categoryStore.getCategor2List(category1Id.value as number)
}

// 获取三级分类数据
const getCategory3List = () => {
  // 二级分类切换，需要重置三级的数据
  category3List.value = []
  category3Id.value = ''

  // 调用 action，获取三级分类数据
  categoryStore.getCategor3List(category2Id.value as number)
}

onMounted(() => {
  categoryStore.getCategory1List()
})
</script>

<script lang="ts">
export default {
  name: 'VCategory'
}
</script>

<style lang="scss" scoped></style>
